<template>
  <a-spin :spinning="confirmLoading">
    <JFormContainer :disabled="disabled">
      <template #detail>
        <a-form ref="formRef" class="antd-modal-form" :labelCol="labelCol" :wrapperCol="wrapperCol" name="CReimbursementForm">
          <a-row>


            <a-col :span="12">
              <a-form-item label="项目" v-bind="validateInfos.projectId" id="CReimbursementForm-projectId" name="projectId">
                <a-select
                  :disabled="disabledFlag"
                  placeholder="请选择"
                  style="width: 100%"
                  v-model:value="formData.projectId"
                  :showSearch="true"
                  :options="projectList"
                  optionFilterProp="label"
                  @change="loadSubProjectList"
                ></a-select>
              </a-form-item>
            </a-col>


            <a-col :span="12" >
              <a-form-item label="子项目" v-bind="validateInfos.subProjectId" id="CReimbursementForm-subProjectId" name="subProjectId">
                <a-select
                  :disabled="disabledFlag"
                  placeholder="请选择"
                  style="width: 100%"
                  v-model:value="formData.subProjectId"
                  :showSearch="true"
                  :options="subProjectList"
                  optionFilterProp="label"
                ></a-select>
              </a-form-item>
            </a-col>

            <a-col :span="12" >
              <a-form-item label="总包主体" v-bind="validateInfos.companyId" id="CReimbursementForm-companyId" name="companyId">
                <a-select
                  :disabled="disabledFlag"
                  placeholder="请选择"
                  style="width: 100%"
                  v-model:value="formData.companyId"
                  :showSearch="true"
                  :options="companyList"
                  optionFilterProp="label"
                ></a-select>
              </a-form-item>
            </a-col>


            <a-col :span="12">
              <a-form-item label="报销名称" v-bind="validateInfos.reimbursementName" id="CReimbursementForm-reimbursementName" name="reimbursementName">
                <a-input :disabled="disabledFlag" v-model:value="formData.reimbursementName" placeholder="请输入报销名称"  allow-clear ></a-input>
              </a-form-item>
            </a-col>
						<a-col :span="12">
							<a-form-item label="报销金额" v-bind="validateInfos.amount" id="CReimbursementForm-amount" name="amount">
								<a-input-number :disabled="disabledFlag" v-model:value="formData.amount" placeholder="请输入报销金额" style="width: 100%" />
							</a-form-item>
						</a-col>
						<a-col :span="12">
							<a-form-item label="附件" v-bind="validateInfos.filePath" id="CReimbursementForm-filePath" name="filePath">
								<j-upload :disabled="disabledFlag" v-model:value="formData.filePath"   ></j-upload>
							</a-form-item>
						</a-col>

						<a-col :span="12">
							<a-form-item label="报销类型" v-bind="validateInfos.reimbursementType" id="CReimbursementForm-reimbursementType" name="reimbursementType">
								 <j-dict-select-tag showSearch="true"   :disabled="disabledFlag" v-model:value="formData.reimbursementType" dictCode="reimbursement_type" placeholder="请选择报销类型"  allow-clear />
							</a-form-item>
						</a-col>
            <a-col :span="12">
              <a-form-item label="报销描述" v-bind="validateInfos.description" id="CReimbursementForm-description" name="description">
                <a-textarea :disabled="disabledFlag" v-model:value="formData.description" :rows="4" placeholder="请输入报销描述" />
              </a-form-item>
            </a-col>

            <a-divider >收款银行信息</a-divider >
            <a-col :span="12">
              <a-form-item label="银行名称" v-bind="validateInfos.bankName" id="CReimbursementForm-bankName" name="bankName">
                <j-dict-select-tag showSearch="true"  :disabled="disabledFlag"  v-model:value="formData.bankName" dictCode="bank_name" placeholder="请选择银行名称"  allow-clear />
              </a-form-item>
            </a-col>
            <a-col :span="12">
              <a-form-item label="支行信息" v-bind="validateInfos.bankBranch" id="CReimbursementForm-bankBranch" name="bankBranch">
                <a-input v-model:value="formData.bankBranch" :disabled="disabledFlag" placeholder="请输入支行信息"  allow-clear ></a-input>
              </a-form-item>
            </a-col>
            <a-col :span="12">
              <a-form-item label="银行账号" v-bind="validateInfos.accountNumber" id="CReimbursementForm-accountNumber" name="accountNumber">
                <a-input v-model:value="formData.accountNumber" :disabled="disabledFlag" placeholder="请输入银行账号"  allow-clear ></a-input>
              </a-form-item>
            </a-col>
            <a-col :span="12">
              <a-form-item label="开户人名称" v-bind="validateInfos.accountHolderName" id="CReimbursementForm-accountHolderName" name="accountHolderName">
                <a-input v-model:value="formData.accountHolderName" :disabled="disabledFlag" placeholder="请输入开户人名称"  allow-clear ></a-input>
              </a-form-item>

            </a-col>

          </a-row>

          <div  v-if="formData.id && disabledFlag ===true" >
          <a-divider >审核</a-divider >
          <a-row  v-if="formData.id && disabledFlag ===true">
            <a-col :span="24">
              <a-form-item label="审核" v-bind="validateInfos.auditStatus" id="CReimbursementForm-auditorDescription" name="auditorDescription">
                <a-radio-group v-model:value="formData.auditStatus"  name="radioGroup">
                  <a-radio value="同意">同意</a-radio>
                  <a-radio value="驳回">驳回</a-radio>
                </a-radio-group>
              </a-form-item>
            </a-col>
            <a-col :span="24">
              <a-form-item label="审核备注" v-bind="validateInfos.auditorDescription" id="CReimbursementForm-auditorDescription" name="auditorDescription">
                <a-textarea v-model:value="formData.auditorDescription" :rows="4" placeholder="请输入审核备注" />
              </a-form-item>
            </a-col>
            <a-col :span="24">
              <a-form-item label="回执文件" v-bind="validateInfos.receiptFile" id="CReimbursementForm-receiptFile" name="receiptFile">
                <j-upload v-model:value="formData.receiptFile"   dragger="true"  :show-upload-list="{ showDownloadIcon: true, showRemoveIcon: true }" ></j-upload>
              </a-form-item>
            </a-col>
          </a-row>
          </div>

        </a-form>
      </template>
    </JFormContainer>
  </a-spin>
</template>

<script lang="ts" setup>
  import { ref, reactive, defineExpose, nextTick, defineProps, computed, onMounted } from 'vue';
  import { defHttp } from '/@/utils/http/axios';
  import { useMessage } from '/@/hooks/web/useMessage';
  import JDictSelectTag from '/@/components/Form/src/jeecg/components/JDictSelectTag.vue';
  import JUpload from '/@/components/Form/src/jeecg/components/JUpload/JUpload.vue';
  import { getValueType } from '/@/utils';
  import { saveOrUpdate } from '../CReimbursement.api';
  import { Form } from 'ant-design-vue';
  import JFormContainer from '/@/components/Form/src/container/JFormContainer.vue';
  import { getCompanyInfoList, getProjectList, getSubProjectList } from '@/views/common.api';
  const props = defineProps({
    formDisabled: { type: Boolean, default: false },
    formData: { type: Object, default: () => ({})},
    formBpm: { type: Boolean, default: true }
  });
  const formRef = ref();
  const useForm = Form.useForm;
  const disabledFlag = ref(false)
  const emit = defineEmits(['register', 'ok']);
  const formData = reactive<Record<string, any>>({
    id: '',
    reimbursementName: '',   
    projectId: undefined,
    subProjectId: undefined,
    companyId: undefined,
    amount: undefined,
    filePath: '',   
    description: '',   
    auditStatus: '',   
    auditor: '',   
    auditorDescription: '',   
    receiptFile: '',   
    reimbursementType: '',   
    userId: '',   
    auditorDate: '',
    bankName: '',
    bankBranch: '',
    accountNumber: '',
    accountHolderName: '',

  });
  const { createMessage } = useMessage();
  const labelCol = ref<any>({ xs: { span: 24 }, sm: { span: 5 } });
  const wrapperCol = ref<any>({ xs: { span: 24 }, sm: { span: 16 } });
  const confirmLoading = ref<boolean>(false);
  //表单验证
  const validatorRules = reactive({
    reimbursementName: [{ required: true, message: '请输入报销名称!'},],
    amount: [{ required: true, message: '请输入报销金额!'},],
  });
  const { resetFields, validate, validateInfos } = useForm(formData, validatorRules, { immediate: false });

  // 表单禁用
  const disabled = computed(()=>{
    if(props.formBpm === true){
      if(props.formData.disabled === false){
        return false;
      }else{
        return true;
      }
    }
    return props.formDisabled;
  });

  
  /**
   * 新增
   */
  function add() {
    disabledFlag.value = false
    edit({});
  }

  /**
   * 编辑
   */
  function edit(record,title) {
    loadProjectList()
    if (record != undefined) {
      if (record.projectId != undefined &&
        record.projectId != null) {
        loadSubProjectList(record.projectId);
      }
    }
    nextTick(() => {
      resetFields();
      const tmpData = {};
      Object.keys(formData).forEach((key) => {
        if(record.hasOwnProperty(key)){
          if("companyId" ===key){
            tmpData["companyId"] = record["companyId"]
          }else {
            tmpData[key] = record[key]
          }
        }
      })
      //赋值
      Object.assign(formData, tmpData);
    });
    if(record.id){
      disabledFlag.value = false
    }
    debugger
    if(title.value ==='详情'){
      disabledFlag.value = true
    }
  }


  /**
   * 审批
   * @param record
   */
  function approval(record) {
    debugger
    loadProjectList()
    if (record != undefined) {
      if (record.projectId != undefined &&
        record.projectId != null) {
        loadSubProjectList(record.projectId);
      }
    }
    nextTick(() => {
      resetFields();
      const tmpData = {};
      Object.keys(formData).forEach((key) => {
        if(record.hasOwnProperty(key)){
          if("companyId" ===key){
            tmpData["companyId"] = record["companyId"]
          }else {
            tmpData[key] = record[key]
          }

        }
      })
      //赋值
      Object.assign(formData, tmpData);
    });
    if(record.id){
      disabledFlag.value = true
    }
  }

  /**
   * 提交数据
   */
  async function submitForm() {
    try {
      // 触发表单验证
      await validate();
    } catch ({ errorFields }) {
      if (errorFields) {
        const firstField = errorFields[0];
        if (firstField) {
          formRef.value.scrollToField(firstField.name, { behavior: 'smooth', block: 'center' });
        }
      }
      return Promise.reject(errorFields);
    }
    confirmLoading.value = true;
    const isUpdate = ref<boolean>(false);
    //时间格式化
    let model = formData;
    if (model.id) {
      isUpdate.value = true;
    }
    //循环数据
    for (let data in model) {
      //如果该数据是数组并且是字符串类型
      if (model[data] instanceof Array) {
        let valueType = getValueType(formRef.value.getProps, data);
        //如果是字符串类型的需要变成以逗号分割的字符串
        if (valueType === 'string') {
          model[data] = model[data].join(',');
        }
      }
    }
    await saveOrUpdate(model, isUpdate.value)
      .then((res) => {
        if (res.success) {
          createMessage.success(res.message);
          emit('ok');
        } else {
          createMessage.warning(res.message);
        }
      })
      .finally(() => {
        confirmLoading.value = false;
      });
  }

  /**
   * 加载 主项目下拉
   */
  const projectList = ref([])
  async function loadProjectList(){
    projectList.value = []
    projectList.value = await getProjectList()
  }
  /**
   * 加载 子主项目 下拉
   */
  const subProjectList = ref([])
  async function loadSubProjectList(projectId){
    formData.subProjectId=undefined
    formData.companyId=undefined
    subProjectList.value = []
    const params = {'projectId':projectId}
    subProjectList.value = await getSubProjectList(params)
    loadCompanyList(projectId)
  }

  /**
   * 加载 总包商
   */
  const companyList = ref([])
  async function loadCompanyList(projectId){
    companyList.value = []
    const params = {'projectId':projectId}
    companyList.value = await getCompanyInfoList(params)
  }


  defineExpose({
    add,
    edit,
    approval,
    submitForm,
    disabledFlag,
    loadProjectList,
    loadSubProjectList,
    loadCompanyList,
    companyList,
  });
</script>

<style lang="less" scoped>
  .antd-modal-form {
    padding: 14px;
  }
</style>
